package models.base;

import facade.AppContext;
import models.common.BaseModel;
import models.constants.DeletedStatus;
import org.apache.commons.lang.StringUtils;

import javax.persistence.*;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * Created by weiwei on 2018/02/08.
 */
@Entity
@Table(name = "admin_role_operates")
public class AdminRoleOperate extends BaseModel {
    /**
     * 关联角色
     */
    @ManyToOne
    @JoinColumn(name = "role_id")
    public Role role;

    /**
     * 角色业务操作
     */
    @ManyToOne
    @JoinColumn(name = "business_id")
    public AdminBusiness business;
    @Transient
    public String businessId;

    /**
     * 是否具有查询权限
     */
    @Column(name = "is_search")
    public Boolean isSearch;
    /**
     * 是否具有新增记录权限
     */
    @Column(name = "is_add")
    public Boolean isAdd;
    /**
     * 是否具有编辑记录权限
     */
    @Column(name = "is_edit")
    public Boolean isEdit;
    /**
     * 是否具有删除记录权限
     */
    @Column(name = "is_delete")
    public Boolean isDelete;

    public AdminRoleOperate() {

    }

    public static void create(Role role,List<AdminRoleOperate> businessList){
        deleteByRoleId(role.id);
        if(businessList != null && businessList.size()>0){
            for (AdminRoleOperate roleOperate : businessList) {
                if(roleOperate.businessId != null){
                    AdminBusiness business = AdminBusiness.findOne(roleOperate.businessId);
                    if(business != null){
                        roleOperate.business = business;
                        roleOperate.role = role;
                        roleOperate.isAdd = roleOperate.isAdd == null?false:roleOperate.isAdd;
                        roleOperate.isEdit = roleOperate.isEdit == null?false:roleOperate.isEdit;
                        roleOperate.isDelete = roleOperate.isDelete == null?false:roleOperate.isDelete;
                        roleOperate.isSearch = true;
                        roleOperate.save();
                    }
                }
            }

        }
    }
    /**
     * 根据角色ID删除角色操作
     *
     * @param roleId
     */
    public static void deleteByRoleId(String roleId) {
        AdminUser loginUser = AppContext.currentUser();
        List<AdminRoleOperate> operateList = findByRoleId(roleId);
        if(operateList.size()>0){
            for (AdminRoleOperate operate : operateList) {
                operate.deleted = DeletedStatus.DELETED;
                operate.modifyAt = new Date();
                operate.modifyUser = loginUser;
                operate.save();
            }
        }
    }

    /**
     * 根据角色Id加载角色操作
     *
     * @param roleId
     * @return
     */
    public static List<AdminRoleOperate> findByRoleId(String roleId) {
        if(StringUtils.isEmpty(roleId)) return Collections.emptyList();
        return find("deleted = ?1 and role.id = ?2",DeletedStatus.UN_DELETED, roleId).fetch();
    }

}
